1 module about_concurrency; 2 3 import dunit; 4 import helpers; 5 6 import std.concurrency; 7 import core.thread; 8 9 //this function will run in another thread 10 //also showing simple message passing 11 void worker2xFunc(Tid tid) 12 { 13 int value = 0; 14 while (value >= 0) 15 { 16 value = receiveOnly!int(); 17 auto result = value * 2; 18 tid.send(result); 19 } 20 } 21 22 //this function will run in another thread 23 //also showing message passing with wait and timeout 24 void workerSlowFunc(Tid tid) 25 { 26 //tid.send("starting..."); 27 Thread.sleep(dur!("msecs")(500),); 28 tid.send("done!"); 29 } 30 31 class AboutConcurrency 32 { 33 mixin UnitTest; 34 35 @Test void collect_doubles() 36 { 37 Tid worker = spawn(&worker2xFunc, thisTid); 38 int sum = 0; 39 foreach (value; 1 .. 3) 40 { 41 worker.send(value); 42 auto result = receiveOnly!int(); 43 sum += result; 44 } 45 worker.send(-1); //signal worker to end 46 assertEquals(sum, FILL_IN_THIS_NUMBER); 47 } 48 49 @Test void wait_for_result() 50 { 51 Tid worker = spawn(&workerSlowFunc, thisTid); 52 bool received = false; 53 while (!received) 54 { 55 received = receiveTimeout(dur!("msecs")(100), (string message) { 56 assertEquals(message,FILL_IN_THIS_STRING); 57 }); 58 59 if (!received) { 60 import std.stdio : write; 61 write("."); 62 } 63 64 } 65 66 } 67 68 }